package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"time"
)

//User 是VPgame账户信息
type User struct {
	Name   string
	Passwd string
	Cookie []string
}

func main() {
	//	locale files
	path := os.Getenv("HOME")
	if _, err := os.Stat(path); err != nil {
		os.Mkdir(path, 0755)
	}
	var logFile, infoFile *os.File
	var err error
	if _, err := os.Stat(path + "/vpgame.log"); err == nil {
		logFile, err = os.OpenFile(path+"/vpgame.log", os.O_RDWR|os.O_APPEND, 0644)
	} else {
		logFile, err = os.Create(path + "/vpgame.log")
	}
	defer logFile.Close()
	if err != nil {
		fmt.Println("panic when do vpgame.log")
		panic(err)
	}
	var jsonInfo []byte
	if _, err := os.Stat(path + "/vpgame_users.json"); err == nil {
		jsonInfo, _ = ioutil.ReadFile(path + "/vpgame_users.json")
		infoFile, err = os.OpenFile(path+"/vpgame_users.json", os.O_WRONLY, 0644)
		defer infoFile.Close()
		infoFile.Read(jsonInfo)
	} else {
		infoFile, err = os.Create(path + "/vpgame_users.json")
		user := make([]User, 1)
		user[0].Name = "UserName"
		user[0].Passwd = "PassWord"
		user[0].Cookie = append(user[0].Cookie, "cookie info. This is just a example, plealse complete your login info.")
		jsonInfo, _ := json.MarshalIndent(user, "", "\t")
		infoFile.Write(jsonInfo)
		fmt.Println("plealse complete your login info.")
		return
	}

	if err != nil {
		fmt.Println("panic when doing vpgame_users.json")
		panic(err)
	}
	logFile.WriteString("Start at:" + time.Now().String() + "\n")

	//	cookie
	user := []User{}
	if err = json.Unmarshal(jsonInfo, &user); err != nil {
		fmt.Println("panic when Unmarshal jsonInfo")
		panic(err)
	}
	for _, rawUser := range user {
		fmt.Println(rawUser.Name)
		fmt.Println(rawUser.Passwd)
		rawUser.Cookie = append(rawUser.Cookie, "add")
		fmt.Println(rawUser.Cookie)
	}

	// cookieJar, _ := cookiejar.New(nil)
	// var cookies []*http.Cookie
	// if _, err := os.Stat(path + "/baidu_sign_cookie.txt"); err == nil {
	// 	rawCookie, _ := ioutil.ReadFile(path + "/baidu_sign_cookie.txt")
	// 	rawCookieList := strings.Split(string(rawCookie), "\n")
	// 	for _, rawCookieLine := range rawCookieList {
	// 		rawCookieInfo := strings.SplitN(rawCookieLine, "=", 2)
	// 		if len(rawCookieInfo) < 2 {
	// 			continue
	// 		}
	// 		cookies = append(cookies, &http.Cookie{
	// 			Name:  rawCookieInfo[0],
	// 			Value: rawCookieInfo[1],
	// 		})
	// 	}
	// 	url, _ := url.Parse("http://baidu.com")
	// 	cookieJar.SetCookies(url, cookies)
	// 	if login.GetLoginStatus(cookieJar) {
	// 		needLogin = false
	// 		fmt.Println("Using cookie saved in baidu_sign_cookie.txt...")
	// 	}
	// }
}
